const gulp = require('gulp')
const sass = require('gulp-sass');
const cleanCSS = require('gulp-clean-css');
const rename = require('gulp-rename');
const autoprefixer = require('gulp-autoprefixer');
const babel = require('gulp-babel')
const ts = require('gulp-typescript')
const del = require('del')
const through = require('through2')
const tsconfig = require('./tsconfig.json')

// 删除lib下所有文件
function clean() {
  return del('./lib/**')
}

// 构建样式
function buildStyle() {
  return gulp.src('./src/styles/index.scss')
    .pipe(sass())
    .pipe(autoprefixer())
    .pipe(cleanCSS())
    .pipe(rename('ibz-ui-ionic.css'))
    .pipe(gulp.dest('./lib/'));
}

// 拷贝静态资源
function copyAssets() {
  return gulp
    .src('./src/assets/**/*')
    .pipe(gulp.dest('lib/assets'))
    .pipe(gulp.dest('lib/es/assets'))
    .pipe(gulp.dest('lib/cjs/assets'))
}

// 构建es
function buildES() {
  const tsProject = ts({
    ...tsconfig.compilerOptions,
    module: 'ESNext',
  })
  return gulp
    .src(['src/**/*.{ts,tsx}'])
    .pipe(tsProject)
    .pipe(babel())
    .pipe(gulp.dest('lib/es/'))
}

// 构建cjs
function buildCJS() {
  return gulp
    .src(['lib/es/**/*.js'])
    .pipe(
      babel({
        'plugins': ['@babel/plugin-transform-modules-commonjs'],
      })
    )
    .pipe(gulp.dest('lib/cjs/'))
}

// 构建声明文件
function buildDeclaration() {
  const tsProject = ts({
    ...tsconfig.compilerOptions,
    declaration: true,
    emitDeclarationOnly: true
  })
  return gulp
    .src(['src/**/*.{ts,tsx}'])
    .pipe(tsProject)
    .pipe(gulp.dest('lib/types/'))
}

// 执行构建任务
exports.default = gulp.series(
  clean,
  buildES,
  gulp.parallel(buildCJS, buildDeclaration, buildStyle),
  copyAssets
)
